<?php
namespace lib;
class User{
    private $io=null;
    private $users=[];
    function __construct($io){
        $this->io=$io;
    }
    /**
     * 增加设备用户
     * @param string  socket_id socket连接ID
     * @param integer member_id 用户ID
     * @param integer device_id 设备ID
     */
    function add($socket_id,$member_id,$device_id){
        if(isset($this->users[$member_id])){
            $this->users[$member_id][$device_id]=[$socket_id,$device_id];
        }else{
            $this->users[$member_id]=[
                $device_id=>[$socket_id,$device_id],
            ];
        }
        // 同步web服务器用户在线设备
        $this->syncDevices($member_id);
    }
    /**
     * 移除设备用户
     * @param integer member_id 用户ID
     * @param integer device_id 设备ID
     */
    function remove($member_id,$device_id){
        $users=$this->users;
        if(isset($users[$member_id])&&isset($users[$member_id][$device_id])){
            unset($this->users[$member_id][$device_id]);
        }
    }
    /**
     * 获取用户socket.id 实现单聊
     * @param integer member_id 用户ID
     * @param integer device_id 设备ID
     */
    function getSocketId($member_id,$device_id){
        if(!$member_id||!$device_id)return;
        $users=$this->users;
        if(isset($users[$member_id])){
            if(isset($users[$member_id][$device_id])){
                return $users[$member_id][$device_id][0];
            }
        }
    }
    /**
     * 同步web服务器用户在线设备
     * @param {integer} member_id 用户ID
     */
    function syncDevices($member_id){
        if(isset($this->users[$member_id])){
            $devices=$this->users[$member_id];
            $ids=array_map(function($n){
                return (string)$n;
            }, array_keys($devices));
            $this->io->to($member_id.'admin')->emit('getUsers',$ids);
        }
    }
}